package com.wuyan.warriorsoffate.data

import android.content.Context
import android.os.Environment
import android.util.Log
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.window.Dialog
import androidx.core.content.edit
import com.wuyan.warriorsoffate.ui.theme.WeTheme
import com.wuyan.warriorsoffate.ui.view.TextFieldBase
import com.wuyan.warriorsoffate.ui.view.WeButton
import com.wuyan.warriorsoffate.ui.view.WeColumn
import com.wuyan.warriorsoffate.ui.view.WeText
import java.io.File
import java.io.IOError
import java.io.IOException

object Config {
    private val initSaveDir= "游戏"
    private val initSaveFileName = "吞食天地1.nes"
    var saveDir= mutableStateListOf("")
    var saveFileName= mutableStateOf(initSaveFileName)
    fun saveData(data:ByteArray):Boolean{
        val saveDirTemp=getSaveDir()
        if (!saveDirTemp.isDirectory){
            if (!saveDirTemp.mkdirs()){
                msgInfoText="父文件夹创建失败：${saveDirTemp.path}"
                msgInfoSate=true
                return false
            }
        }
        val saveFile =File(saveDirTemp, saveFileName.value)
        if (saveFile.isFile){
            if (!saveFile.delete()){
                msgInfoText="保存文件删除原文件失败：${saveFile.path}"
                msgInfoSate=true
                return false
            }
        }
        if (!saveFile.createNewFile()){
            msgInfoText="保存文件创建失败：${saveFile.path}"
            msgInfoSate=true
            return false
        }
        val outputStream =saveFile.outputStream()
        outputStream.write(data)
        outputStream.close()
        return true
    }
    fun getData():ByteArray?{
        val saveDirTemp=getSaveDir()
        if (!saveDirTemp.isDirectory){
            if (!saveDirTemp.mkdirs()){
                msgInfoText="父文件夹创建失败：${saveDirTemp.path}"
                msgInfoSate=true
                return null
            }
        }
        val saveFile =File(saveDirTemp, saveFileName.value)
        return saveFile.readBytes()
    }
    //获取保存文件所在目录
    fun getSaveDir():File{
        val strBuilder=StringBuilder()
        for (i in saveDir.indices){
            strBuilder.append(saveDir[i])
        }
        return File(Environment.getExternalStorageDirectory(),strBuilder.toString())
    }
    //获取
    fun dirToString():String{
        val strBuilder=StringBuilder()
        for (i in saveDir.indices){
            if (saveDir[i]!=""){
                strBuilder.append(saveDir[i])
                if (i!= saveDir.size-1){
                    strBuilder.append("/")
                }
            }
        }
        return strBuilder.toString()
    }
    fun init(context: Context){
        //读取配置文件没有就创建配置文件
        val sharedPreferences=context.getSharedPreferences("user", Context.MODE_PRIVATE)
        val filePath= sharedPreferences.getString("saveDir", initSaveDir)!!
        saveFileName.value= sharedPreferences.getString("fileName", initSaveFileName)!!
        saveDir.clear()
        for (str in filePath.split("/")){
            saveDir.add(str)
        }
        val temp = getSaveDir()
        if (!temp.isDirectory){
            if (!temp.mkdirs()){
                msgInfoText="文件夹创建失败：${temp.path}"
                msgInfoSate=true
            }
        }
    }
    fun saveConfig(context: Context){
        //读取配置文件没有就创建配置文件
        val sharedPreferences=context.getSharedPreferences("user", Context.MODE_PRIVATE)
        sharedPreferences.edit(true) {
            this.putString("saveDir", dirToString())
            this.putString("fileName", saveFileName.value)
        }
    }
    fun newFile(fileName:String):Boolean{
        val saveDirTemp=File(getSaveDir(),fileName)
        if (!saveDirTemp.isDirectory){
            if (!saveDirTemp.mkdirs()){
                msgInfoText="父文件夹创建失败：${saveDirTemp.path}"
                msgInfoSate=true
                return false
            }
        }
        return true
    }
    var msgInfoSate by mutableStateOf(false)
    var msgInfoText = ""
    var state= mutableStateOf(SelectFileDialogType.None)
}
enum class SelectFileDialogType{
    None,//
    Open,//
    SaveAs,//
    Reset;//
    override fun toString(): String {
        return when(this){
            Open->"选择打开文件"
            SaveAs->"选择保存文件"
            Reset->"重置"
            else->"None"
        }
    }
}
@ExperimentalAnimationApi
@Composable
fun SelectFileDialog(state: MutableState<SelectFileDialogType>,nes:NesViewModel){
    val context=LocalContext.current
    if (state.value!=SelectFileDialogType.None){
        if (state.value==SelectFileDialogType.Reset){
            val data=context.assets.open("吞食天地1.NES").readBytes()
            nes.refresh(data)
        }else{
            Dialog(onDismissRequest = {
                state.value=SelectFileDialogType.None
                Config.saveConfig(context)
            }) {
                val listFile = mutableStateListOf<File>()
                Column(modifier = Modifier
                    .fillMaxSize()
                    .background(
                        WeTheme.colors.bg,
                        shape = RoundedCornerShape(WeTheme.weDp.paddingSmall)
                    )
                    .padding(WeTheme.weDp.paddingMedium)) {
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(WeTheme.weDp.paddingMedium)) {
                        val isNew= remember {
                            mutableStateOf(false)
                        }
                        if (isNew.value){
                            Row(modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight(),
                                verticalAlignment = Alignment.CenterVertically) {
                                val newFileName= remember {
                                    mutableStateOf("")
                                }
                                WeButton(onClick = {
                                    isNew.value=false
                                }, text = "关闭")
                                TextFieldBase(value = newFileName.value, onValueChange = {
                                    newFileName.value=it
                                }, modifier = Modifier.weight(1.0f))
                                WeButton(onClick = {
                                    isNew.value=false
                                    if (newFileName.value!=""){
                                        if (Config.newFile(newFileName.value)){
                                            listFile.add(File(Config.getSaveDir(),newFileName.value))
                                        }
                                    }
                                }, text = "确认")
                            }
                        }else{
                            Box(modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentHeight()) {
                                WeText(text = state.value.toString(), modifier = Modifier.align(Alignment.Center))
                                WeButton(onClick = {
                                    state.value=SelectFileDialogType.None
                                    Config.saveConfig(context)
                                }, text = "关闭", modifier = Modifier.align(Alignment.CenterStart))
                                WeButton(onClick = {
                                    isNew.value=true
                                }, text = "新建文件夹", modifier = Modifier.align(Alignment.CenterEnd))
                            }
                        }

                    }
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(modifier = Modifier.clickable {
                            Config.saveDir.clear()
                        }){
                            WeText(text = "/", color = if (Config.saveDir.isEmpty()) WeTheme.colors.label1 else WeTheme.colors.text)
                            Icon(painter = painterResource(id = com.wuyan.warriorsoffate.R.drawable.next),
                                contentDescription = "下一级",
                                modifier = Modifier.size(WeTheme.weDp.iconDp/2),
                                tint = WeTheme.colors.text)
                        }
                        for (i in Config.saveDir.indices){
                            Row(modifier = Modifier.clickable {
                                if (i<Config.saveDir.size-1){
                                    Config.saveDir.removeRange(i+1,Config.saveDir.size)
                                }
                            }){
                                WeText(text = Config.saveDir[i], color = if (i==Config.saveDir.size-1) WeTheme.colors.label1 else WeTheme.colors.text)
                                Icon(painter = painterResource(id = com.wuyan.warriorsoffate.R.drawable.next),
                                    contentDescription = "下一级",
                                modifier = Modifier.size(WeTheme.weDp.iconDp/2),
                                tint = WeTheme.colors.text)
                            }
                        }
                    }
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .weight(1.0f)){
                        WeColumn(modifier = Modifier
                            .fillMaxSize()) {
                            val dir=Config.getSaveDir()
                            val temp=dir.listFiles()
                            listFile.clear()
                            if (temp!=null){
                                temp.sort()
                                listFile.addAll(temp)
                            }
                            if (listFile.isNotEmpty()){
                                items(listFile.size){i->
                                    Row(modifier = Modifier
                                        .padding(WeTheme.weDp.marginSmall)
                                        .fillMaxWidth()
                                        .clickable {
                                            if (listFile[i].isDirectory) {
                                                Config.saveDir.add(listFile[i].name)
                                            } else if (listFile[i].isFile) {
                                                Config.saveFileName.value = listFile[i].name
                                            }
                                        }) {
                                        if (listFile[i].isDirectory){
                                            Icon(painter = painterResource(id = com.wuyan.warriorsoffate.R.drawable.dir),
                                                contentDescription = "文件夹",
                                                modifier = Modifier.size(WeTheme.weDp.iconDp/2),
                                                tint = WeTheme.colors.text)
                                        }else if (listFile[i].isFile){
                                            Icon(painter = painterResource(id = com.wuyan.warriorsoffate.R.drawable.file),
                                                contentDescription = "文件",
                                                modifier = Modifier.size(WeTheme.weDp.iconDp/2),
                                                tint = WeTheme.colors.text)
                                        }
                                        WeText(text = listFile[i].name, color = WeTheme.colors.text)
                                    }
                                }
                            }
                        }
                    }
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .wrapContentHeight(),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        TextFieldBase(value = Config.saveFileName.value, onValueChange = {
                            Config.saveFileName.value=it
                        }, modifier = Modifier.weight(1.0f))
                        WeButton(onClick = {
                            if (state.value==SelectFileDialogType.SaveAs){
                                if(Config.saveData(nes.toByteArray())){
                                    val temp=File(Config.getSaveDir(),Config.saveFileName.value)
                                    var isHas=false
                                    for (i in listFile.indices){
                                        if(listFile[i].path==temp.path){
                                            isHas=true
                                            break
                                        }
                                    }
                                    if (!isHas){
                                        listFile.add(temp)
                                    }
                                }
                            }else{
                                val data=Config.getData()
                                if (data==null){
                                    Config.msgInfoText ="读取文件失败：${Config.dirToString()+"/"+Config.saveFileName.value}"
                                    Config.msgInfoSate =true
                                }else{
                                    nes.refresh(data)
                                }
                                state.value=SelectFileDialogType.None
                            }
                        },
                            text = if (state.value==SelectFileDialogType.SaveAs) "保存" else "确认")
                    }
                }
            }
        }

    }
}